package com.jsjosem.aftersales.ui.event;

import static com.jsjosem.aftersales.constant.Command.REFRESH_EVENT_LIST;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.jsjosem.aftersales.R;
import com.jsjosem.aftersales.adapter.EventAdapter;
import com.jsjosem.aftersales.api.EventApi;
import com.jsjosem.aftersales.api.RetrofitClient;
import com.jsjosem.aftersales.data.response.EventResponse;
import com.jsjosem.aftersales.data.response.PageResponse;
import com.jsjosem.aftersales.listener.IListener;
import com.jsjosem.aftersales.listener.ListenerManager;
import com.jsjosem.aftersales.request.AsyncRequest;
import com.jsjosem.aftersales.ui.notifications.ServiceEventInfoActivity;
import com.jsjosem.aftersales.utils.PageUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.wang.avi.AVLoadingIndicatorView;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Retrofit;

public class EventListFragment extends Fragment implements IListener {
    private View view;
    private RecyclerView recyclerView;
    private SmartRefreshLayout smartRefreshLayout;
    private Retrofit retrofit;
    private String status;
    private List<EventResponse> eventResponseList = new ArrayList<>();
    private EventAdapter eventAdapter;
    private Dialog loadingDialog;
    private String aboutMe;
    private int currentPage = 1;

    public EventListFragment(String status) {
        this.status = status;
    }

    public static EventListFragment newInstance(String status) {
        return new EventListFragment(status);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_page_list, container, false);
        initView();
        initAdapter();
        initData(currentPage++);
        loadMore();
        return view;
    }

    private void initView() {
        smartRefreshLayout = view.findViewById(R.id.refreshLayout);
        smartRefreshLayout.setEnableAutoLoadMore(false);
        recyclerView = view.findViewById(R.id.ticket_recycler_view);
        retrofit = RetrofitClient.getInstance();
        ListenerManager.getInstance().registerListener(this);
    }

    private void initAdapter() {
        eventAdapter = new EventAdapter(view.getContext(), eventResponseList);
        eventAdapter.setOnItemClickListener((v, position) -> {
            Intent intent = new Intent(getContext(), ServiceEventInfoActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("eventId", eventResponseList.get(position).getId().toString());
            intent.putExtras(bundle);
            startActivity(intent);
        });
        recyclerView.setAdapter(eventAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
    }

    private void initData(int currentPage) {
        loadingShow();
        Log.d("EventListFragment", "status: " + status);
        EventApi eventApi = retrofit.create(EventApi.class);
        Call<PageResponse<EventResponse>> events = eventApi.events(currentPage, 10, status, aboutMe);
        AsyncRequest<PageResponse<EventResponse>> request = new AsyncRequest<>();
        request.sendRequest(events, res -> {
            if (res != null) {
                Long total = res.getCount();
                int totalPage = PageUtils.totalPage(10, total);
                if (currentPage > totalPage) {
                    smartRefreshLayout.finishLoadMoreWithNoMoreData();
                } else {
                    eventResponseList.addAll(res.getData());
                    loadingDialog.dismiss();
                    eventAdapter.notifyDataSetChanged();
                }
                loadingDialog.dismiss();
            }
        }, err -> {
            Toast.makeText(view.getContext(), err.toString(), Toast.LENGTH_SHORT).show();
        });
    }

    public void loadingShow() {
        loadingDialog = new Dialog(view.getContext(), R.style.normal_dialog_style);
        View loadingView = View.inflate(view.getContext(), R.layout.dialog_loading, null);
        loadingDialog.setContentView(loadingView);
        //使得点击对话框外部不消失对话框
        loadingDialog.setCanceledOnTouchOutside(false);
        AVLoadingIndicatorView avi = loadingView.findViewById(R.id.avi);
        avi.show();
        loadingDialog.show();
    }

    private void loadMore() {
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            /**
             * 加载更多
             * @param refreshLayout
             */
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                initData(currentPage++);
                smartRefreshLayout.finishLoadMore();
            }

            /**
             * 下拉刷新
             * @param refreshLayout
             */
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPage = 1;
                eventResponseList.clear();
                initData(currentPage++);
                smartRefreshLayout.finishRefresh();
            }
        });
    }

    @Override
    public void notifyAllActivity(int flag, String data, String message) {
        if (flag == REFRESH_EVENT_LIST) {
            if (data.equals("全部事件")) {
                aboutMe = null;
                currentPage = 1;
                eventResponseList.clear();
                initData(currentPage++);
            }
            if (data.equals("我创建")) {
                aboutMe = "我创建";
                currentPage = 1;
                eventResponseList.clear();
                initData(currentPage++);
            }
            if (data.equals("我负责")) {
                aboutMe = "我负责";
                currentPage = 1;
                eventResponseList.clear();
                initData(currentPage++);
            }
            if (data.equals("我协办")) {
                aboutMe = "我协办";
                currentPage = 1;
                eventResponseList.clear();
                initData(currentPage++);
            }
        }
    }
}
